package com.gimi.cloud.jimi.manage.controller.prod;

import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.UUIDUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.common.utils.reqhead.Util;
import com.gimi.cloud.jimi.dto.product.SecurityInstructionsDTO;
import com.gimi.cloud.jimi.manage.service.prod.SecurityInstructionsService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @auther loongs
 * @date 2018/1/30  13:28
 */
@RestController
@RequestMapping(value = "securityInstructions")
public class SecurityInstructionsController {
    private static Logger logger = LoggerFactory.getLogger(SecurityInstructionsController.class);
    private SecurityInstructionsService securityInstructionsService;
    @Autowired
    public SecurityInstructionsController(SecurityInstructionsService securityInstructionsService) {
        this.securityInstructionsService = securityInstructionsService;
    }

    @RequestMapping(value = "/getSecurityInstructionsPageList")
    public void getSecurityInstructionsPageList(@RequestBody SecurityInstructionsDTO securityInstructionsDTO, HttpServletResponse response) {
        logger.info("获得保障说明列表（分页），入参："+securityInstructionsDTO);
        Response resp = new Response();
        PageInfo<SecurityInstructionsDTO> list=securityInstructionsService.getSecurityInstructionsPageList(securityInstructionsDTO);
        resp.setRes_data(list);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp),response);
    }

    @RequestMapping(value = "/getSecurityInstructionsSingle")
    public void getSecurityInstructionsSingle(@RequestBody SecurityInstructionsDTO securityInstructionsDTO, HttpServletResponse response) {
        logger.info("获得单个保障说明，入参："+securityInstructionsDTO);
        Response resp = new Response();
        SecurityInstructionsDTO newSecurityInstructionsDTO=securityInstructionsService.getSecurityInstructionsSingle(securityInstructionsDTO);
        resp.setRes_data(newSecurityInstructionsDTO);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp),response);
    }

    @RequestMapping(value = "/addOrEditSecurityInstructions")
    public void addOrEditSecurityInstructions(@RequestBody SecurityInstructionsDTO securityInstructionsDTO, HttpServletResponse response) {
        logger.info("添加或者修改保障说明，入参："+securityInstructionsDTO);
        Response resp = new Response();
        boolean result=securityInstructionsService.addOrEditSecurityInstructions(securityInstructionsDTO);
        if(result){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.FAILURE,"新增或者编辑失败，请确认信息后重试！");
        }
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp),response);
    }

    @RequestMapping(value = "/delSecurityInstructions")
    public void delSecurityInstructions(@RequestBody SecurityInstructionsDTO securityInstructionsDTO, HttpServletResponse response) throws MsgException {
        logger.info("删除保障说明，入参："+securityInstructionsDTO);
        Response resp = new Response();
        boolean result=securityInstructionsService.delSecurityInstructions(securityInstructionsDTO);
        if(result){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.FAILURE,"删除保障说明失败，请确认信息后重试！");
        }
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp),response);
    }

    @RequestMapping(value = "/fileUploadSecurityInstructions")
    public void fileUploadSecurityInstructions(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "";
        StandardMultipartHttpServletRequest multipartHttpServletRequest = (StandardMultipartHttpServletRequest) request;
        MultiValueMap multipartFiles = multipartHttpServletRequest.getMultiFileMap();
        for(Object entry : multipartFiles.entrySet()){
            LinkedList<MultipartFile> lists = ((Map.Entry<String, LinkedList<MultipartFile>>) entry).getValue();
            for(MultipartFile file : lists){
                InputStream is = file.getInputStream();
                String uuId = UUIDUtil.get32UUID();
                String dirPath = "securityInstructions";
                String[] originalFilenames = file.getOriginalFilename().split("\\.");
                String fileName = uuId + "." + originalFilenames[originalFilenames.length-1];
                //测试上传时间
                long startTime1=System.currentTimeMillis();
                String result = AliOSSUtil.uploadFile(is,dirPath,fileName);
                long endTime1=System.currentTimeMillis();
                logger.info("上传ad图片到OSS，所用时间： "+(endTime1-startTime1)+"ms");

                long startTime2=System.currentTimeMillis();
                String tempUrl = AliOSSUtil.getFileUrl(result,new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365 * 100));
                long endTime2=System.currentTimeMillis();
                logger.info("获得ad图片的url路径，所用时间： "+(endTime2-startTime2)+"ms");

                url += ","+tempUrl;
                System.out.println("==========>上传结果：" + url);
            }
        }

        Response resp = new Response();
        Map<String,String> data = new HashMap<>();
        data.put("url",url.equals("")?url:url.substring(1));
        resp.setRes_data(data);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }
}
